package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 异步将发布id和用户id写入好友的时间表中
     * @param publishId
     * @param userId
     */
    @Async//开启异步
    public CompletableFuture<String> saveTimeLine(ObjectId publishId, Long userId, long timeMillis) {
        try {
        //查询出当前用户的所有好友信息
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Users> usersList = mongoTemplate.find(query, Users.class);
        if (CollUtil.isEmpty(usersList)){
            return CompletableFuture.completedFuture("ok");
        }

        //遍历好友信息的集合
        for (Users users : usersList) {
            //创建时间线表实体类对象
            TimeLine timeLine = new TimeLine();
            //创建时间
            timeLine.setDate(timeMillis);
            //主键id
            timeLine.setId(ObjectId.get());
            //动态id
            timeLine.setPublishId(publishId);
            //发布用户id
            timeLine.setUserId(userId);

            //保存到好友的时间线表中
            mongoTemplate.save(timeLine,"quanzi_time_line_"+users.getFriendId());
        }
        }catch (Exception e){
            //TODO 出现异常，事务回滚
            log.error("保存时间线表出现错误",e);
            return CompletableFuture.completedFuture("error");
        }

        return CompletableFuture.completedFuture("ok");
    }
}
